import { create } from 'zustand';
import { devtools, persist, createJSONStorage } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';

// 存储配置
export interface StorageConfig {
  name: string;
  version?: number;
  storage?: Storage;
  partialize?: (state: any) => any;
  onRehydrateStorage?: (state: any) => void;
}

// 开发工具配置
export interface DevtoolsConfig {
  name: string;
  enabled?: boolean;
}

// 创建带持久化和开发工具的 store
export function createStoreWithMiddleware<T>(
  initialState: T,
  config?: {
    persist?: StorageConfig;
    devtools?: DevtoolsConfig;
  }
) {
  let store = create<T>();

  // 添加 immer 中间件
  store = store.pipe(immer((set) => set));

  // 添加持久化中间件
  if (config?.persist) {
    store = store.pipe(
      persist((config) => config, {
        name: config.persist.name,
        version: config.persist.version || 1,
        storage: config.persist.storage || localStorage,
        partialize: config.persist.partialize,
        onRehydrateStorage: config.persist.onRehydrateStorage,
        serialize: (state) => JSON.stringify(state),
        deserialize: (str) => JSON.parse(str),
      })
    );
  }

  // 添加开发工具中间件
  if (config?.devtools) {
    store = store.pipe(
      devtools((config) => config, {
        name: config.devtools.name,
        enabled: config.devtools.enabled !== false,
      })
    );
  }

  return store;
}

// 通用的状态选择器
export function createSelector<T, U>(
  selector: (state: T) => U
): (state: T) => U {
  return selector;
}

// 状态重置工具
export function createResetAction<T>(initialState: T) {
  return (set: any) => set(initialState);
}

// 状态部分更新工具
export function createPartialSetAction<T>() {
  return (set: any) => (partialState: Partial<T>) => set(partialState);
}

// 异步操作状态管理
export interface AsyncState<T> {
  data: T | null;
  loading: boolean;
  error: Error | null;
}

export interface AsyncActions<T> {
  setData: (data: T) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: Error | null) => void;
  reset: () => void;
}

// 创建异步状态 slice
export function createAsyncSlice<T>(
  initialData: T | null = null
): {
  state: AsyncState<T>;
  actions: AsyncActions<T>;
} {
  const state: AsyncState<T> = {
    data: initialData,
    loading: false,
    error: null,
  };

  const actions: AsyncActions<T> = {
    setData: (set) => (data: T) => set({ data, error: null }),
    setLoading: (set) => (loading: boolean) => set({ loading }),
    setError: (set) => (error: Error | null) => set({ error }),
    reset: (set) => () => set({ data: null, loading: false, error: null }),
  };

  return { state, actions };
}

// 批量更新工具
export function createBatchActions<T>(
  setState: (updater: (state: T) => T) => void
) {
  return {
    update: (updater: (state: T) => Partial<T>) => {
      setState((state) => ({ ...state, ...updater(state) }));
    },
    merge: (partialState: Partial<T>) => {
      setState((state) => ({ ...state, ...partialState }));
    },
    reset: (initialState: T) => {
      setState(() => initialState);
    },
  };
}

// 状态订阅工具
export function createSubscription<T, U>(
  store: any,
  selector: (state: T) => U,
  callback: (selectedState: U) => void
) {
  let previousValue: U;

  const unsubscribe = store.subscribe(
    (state: T) => selector(state),
    (selectedState: U) => {
      if (selectedState !== previousValue) {
        previousValue = selectedState;
        callback(selectedState);
      }
    }
  );

  return unsubscribe;
}

// 计算属性工具
export function createComputed<T, U>(
  store: any,
  selector: (state: T) => U,
  computeFn: (selectedState: U) => any
) {
  let cachedValue: any;
  let cachedInput: U;

  return (state: T) => {
    const input = selector(state);

    if (input !== cachedInput) {
      cachedInput = input;
      cachedValue = computeFn(input);
    }

    return cachedValue;
  };
}

// 状态验证工具
export function createValidator<T>(
  validators: Record<keyof T, (value: any) => boolean | string>
) {
  return (state: T) => {
    const errors: Record<string, string> = {};

    Object.keys(validators).forEach((key) => {
      const validator = validators[key as keyof T];
      const result = validator(state[key as keyof T]);

      if (result !== true) {
        errors[key] = typeof result === 'string' ? result : '验证失败';
      }
    });

    return {
      isValid: Object.keys(errors).length === 0,
      errors,
    };
  };
}

// 状态历史记录
export interface HistoryEntry<T> {
  state: T;
  timestamp: number;
  action?: string;
}

export function createHistory<T>(maxEntries: number = 50) {
  const history: HistoryEntry<T>[] = [];
  let currentIndex = -1;

  return {
    push: (state: T, action?: string) => {
      // 移除当前索引之后的历史记录
      history.splice(currentIndex + 1);

      // 添加新的历史记录
      history.push({
        state: JSON.parse(JSON.stringify(state)),
        timestamp: Date.now(),
        action,
      });

      // 限制历史记录数量
      if (history.length > maxEntries) {
        history.shift();
      } else {
        currentIndex++;
      }
    },

    undo: (currentState: T) => {
      if (currentIndex > 0) {
        currentIndex--;
        return history[currentIndex].state;
      }
      return currentState;
    },

    redo: (currentState: T) => {
      if (currentIndex < history.length - 1) {
        currentIndex++;
        return history[currentIndex].state;
      }
      return currentState;
    },

    canUndo: () => currentIndex > 0,
    canRedo: () => currentIndex < history.length - 1,
    getHistory: () => [...history],
    clear: () => {
      history.length = 0;
      currentIndex = -1;
    },
  };
}

// 状态同步工具
export function createSync<T>(
  sourceStore: any,
  targetStore: any,
  selector: (state: T) => any,
  transform?: (value: any) => any
) {
  return sourceStore.subscribe(
    selector,
    (value) => {
      const transformedValue = transform ? transform(value) : value;
      targetStore.setState(transformedValue);
    }
  );
}

// 性能优化的状态管理
export function createOptimizedStore<T>(
  initialState: T,
  options: {
    batchSize?: number;
    batchDelay?: number;
    equalityCheck?: (a: any, b: any) => boolean;
  } = {}
) {
  const { batchSize = 10, batchDelay = 16, equalityCheck = Object.is } = options;

  let batchedUpdates: Array<(state: T) => T> = [];
  let batchTimeout: NodeJS.Timeout | null = null;

  const flushBatch = (setState: (updater: (state: T) => T) => void) => {
    if (batchedUpdates.length === 0) return;

    const updates = [...batchedUpdates];
    batchedUpdates = [];

    setState((state) => {
      return updates.reduce((currentState, update) => update(currentState), currentState);
    });
  };

  return create<T>()(
    devtools(
      persist(
        immer((set, get) => ({
          ...initialState,

          // 批量更新
          batchUpdate: (updater: (state: T) => T) => {
            batchedUpdates.push(updater);

            if (!batchTimeout) {
              batchTimeout = setTimeout(() => {
                flushBatch(set);
                batchTimeout = null;
              }, batchDelay);
            }
          },

          // 带缓存的更新
          cachedUpdate: (updater: (state: T) => T) => {
            const currentState = get();
            const newState = updater(currentState);

            if (!equalityCheck(currentState, newState)) {
              set(newState);
            }
          },
        })),
        {
          name: 'optimized-store',
          storage: createJSONStorage(() => localStorage),
          partialize: (state) => {
            // 只持久化部分状态
            const keys = Object.keys(initialState);
            const partial: any = {};
            keys.forEach(key => {
              partial[key] = state[key];
            });
            return partial;
          },
        }
      ),
      { name: 'OptimizedStore' }
    )
  );
}